var express = require('express');
var router = express.Router();
var sqlUtils = require('../util/sqlUtil');
/* GET home page. */
router.get('/', function(req, res, next) {
    res.redirect("/login.html");
});
// 拦截修改密码请求
router.put('/',function(req,res,next){
  var id=req.body.uid,
  old = req.body.old_password,
  newpassword = req.body.new_password,
  again=req.body.again_password;
  
  if(newpassword!=again){
    var resdata={"msg":0};
    res.send(resdata);
  }else if(old==again) {
    var resdata={"msg":-1};
    res.send(resdata);
  }else {
    var sql ="select password from users where id="+id;
  sqlUtils.sqlConnect(sql,function(err,data){
    if (err) {
      console.log(err);
    }else {
      if(JSON.parse(JSON.stringify(data))[0].password==old){
        sqlUtils.sqlConnect("update users set password='"+again+"' where id="+id, function(err, data) {
          if (err) {
            console.log(err);
          }else {
            var resdata={"msg":1};
            res.send(resdata);
          }
        })
      }else {
        var resdata={"msg":-2};
        res.send(resdata);
      }
    }
  })
  }
  
})
// 拦截index请求
router.get('/index.html',function(req,res,next){
  var name=req.session.username;
  if(name==null||name=='undefined'){
    res.redirect("login.html");
  }else {
    // console.log(req.session.id)
    res.render('index',{name: name,id:req.session.uid});
  }
})
// 拦截login.html
router.get('/login.html',function(req,res,next){
  var name=req.session.username;
  if(name==null||name=='undefined'){
    res.render("login",{});
  }else {
    res.redirect('index.html');
  }
})
// 账号验证
router.post('/checkUser',function(req,res,next){
  var username=req.body.username;
  var sql="select * from users where username=?";
  sqlUtils.sqlConnect(sql,[username],function(err,data){
    if(data.length > 0){
      res.send('1');
    }else {
      res.send('0');
    }
  })
})
// 登录
router.post('/login.do',function(req,res,next){
  var username = req.body.username;
  var password=req.body.password;
  var sql="select * from users where username=?";
  var sqlArr=[username];
  sqlUtils.sqlConnect(sql,sqlArr,function(err,data){
    if(data.length>0){
      if(data[0].password==password){
        req.session.username=username;
        req.session.uid=data[0].id;
        var json={"code":200,"msg":1};
        res.send(json);
      }else {
        var json={"code":200,"msg":0};
        res.send(json);
      }
    }else {
      var json={"code":200,"msg":"-1"};
      res.send(json)
    }
  })
})
//退出登录
router.get('/clear',function(req,res){
  req.session.destroy();//设置销毁session对象
  res.sendStatus(200)
})

module.exports = router;
